const Model = require('../models/client-model')
const TorrentModel = require('../models/torrent-model')
const ResponseModel = require('../models/response-model')
const BtClients = require('../utils/btclients/index')

module.exports = {

    // 查询
    'get::/client/list': async function(ctx) {

        const params = ctx.request.query
        
        const whereBuilder = countQuery => {
            if (params.keyword) {
                countQuery.where('name', 'like', `%${params.keyword}%`)
            }
        }

        const list = await Model.list(Model.buildPaging(params) ,whereBuilder)

        ctx.response.body = ResponseModel.success(list)
    },
    // 保存
    'post::/client/save': async function(ctx) {

        const model = ctx.request.body
        let id = model.id
        delete model.id
        
        let oldModel
        if (id) {
            oldModel = await Model.getById(id)
            const updated = await Model.updateBy(model, { id: id })
            model.id = id
        } else {
            const inserted = await Model.insert(model)
            if (inserted && inserted.length > 0) {
                id = inserted[0]
                model.id = inserted[0]
            }
        }

        if (model.id && model.address && model.loginname && model.loginpwd) {
            // 修改的重新获取客户端
            const force = (oldModel != undefined && (oldModel.address !== model.address || oldModel.loginname !== model.loginname || oldModel.loginpwd !== model.loginpwd))
            const client = BtClients.getClient(model, force)
            if (client) {
                let setting = false
                try {
                    setting = await client.getSetting()
                } catch(error) {
                    ctx.response.body = ResponseModel.success({}, `保存成功。但未能连接下载器[${error.message}]`)
                    return
                }
                if (setting) {
                    // setting.version
                    // setting.downloadDir
                    await Model.updateBy({volumeHost: setting.downloadDir}, { id: id })
                }       
            }
        }

        ctx.response.body = ResponseModel.success()
    },
    // 更新部分属性
    'post::/client/update': async function (ctx) {

        const { id, order } = ctx.request.body

        if (id) {
            const updateModel = {}
            if (!isNaN(order)) {
                updateModel.order = order
            }
            const updated = await Model.updateBy(updateModel, { id: id })
        }
        ctx.response.body = ResponseModel.success()
    },
    // 删除
    'get::/client/delete/:id': async function(ctx) {

        const { id } = ctx.request.params
        if (id) {
            const torrentCount = await TorrentModel.count(countQuery => {
                countQuery.where('clientid', id)
            })
            if (torrentCount > 0) {
                ctx.response.body = ResponseModel.failure(`该下载器还有[${torrentCount}]个种子`)
                return
            }
            const deleted = await Model.delete({ id: id })
        }
        ctx.response.body = ResponseModel.success()
    },
    // 选项
    'get::/client/options': async function(ctx) {

        const params = ctx.request.query

        const list = await Model.list(Model.buildPaging(params))

        ctx.response.body = ResponseModel.success(list)
    },
    // 下载器信息
    'get::/client/info/:id': async function(ctx) {
        const { id } = ctx.request.params
        const data = {}
        if (id) {
            const model = await Model.getById(id)
            const client = BtClients.getClient(model)
            if (client) {
                const setting = await client.getSetting()
                if (setting) {
                    data.version = setting.version
                    data.downloadDir = setting.downloadDir
                }       
            }
        }
        ctx.response.body = ResponseModel.success(data)
    },
    // 重新连接下载器
    'get::/client/reconnect/:id': async function(ctx) {
        const { id } = ctx.request.params
        const data = {}
        if (id) {
            const model = await Model.getById(id)
            const client = BtClients.getClient(model, true)
            if (client) {
                const setting = await client.getSetting()
                if (setting) {
                    data.version = setting.version
                    data.downloadDir = setting.downloadDir
                }       
            }
        }
        ctx.response.body = ResponseModel.success(data)
    },
    
}
  